<template>
<div>
  <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>音乐管理</el-breadcrumb-item>
    <el-breadcrumb-item>歌曲管理</el-breadcrumb-item>
    <el-breadcrumb-item>歌曲列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 条件查询   -->
  <el-form :inline="true" :model="query" size="mini" >
    <el-form-item label="歌曲名称:">
      <el-input v-model.trim="query.songName"></el-input>
    </el-form-item>
    <el-form-item label="歌手名称:">
      <el-input v-model.trim="query.singerName"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
      <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
    </el-form-item>
  </el-form>
  <div class="handle_box">
    <el-button size="mini" type="danger" icon="el-icon-minus" @click="handleBatchDel" :disabled="batchDelFlag">批量删除</el-button>
    <el-button size="mini" type="info" icon="el-icon-bottom" @click="handleBatchDel" :disabled="batchDelFlag">导出</el-button>
    <el-button size="mini" type="primary" icon="el-icon-top" @click="handleImport">导入</el-button>
    <el-button size="mini" type="primary" plain icon="el-icon-bottom" @click="handleImport">下载模板</el-button>
  </div>
  <!--  列表数据  -->
  <el-table :data="list" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="40"></el-table-column>
    <el-table-column align="center" prop="songImg" label="封面" width="100">
      <template slot-scope="scope">
        <el-image :src="scope.row.songImg" style="width: 50px;height: 50px;border-radius: 50%"></el-image>
      </template>
    </el-table-column>
    <el-table-column align="center" prop="songName" label="歌曲" width="180"></el-table-column>
    <el-table-column align="center" prop="singerName" label="歌手" width="120">
      <template slot-scope="scope">
        <el-tag type="success" >{{scope.row.singerName}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column align="center" prop="songCategoryName" label="分类" width="90">
      <template slot-scope="scope">
        <el-tag type="info" >{{scope.row.songCategoryName}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column align="center" prop="status" label="状态" width="90">
      <template slot-scope="scope">
        <el-tag v-if="scope.row.status === 1" type="primary">已发布</el-tag>
        <el-tag v-if="scope.row.status === 0" type="danger">未发布</el-tag>
      </template>
    </el-table-column>
    <el-table-column align="center" prop="album" label="专辑" width="130"></el-table-column>
    <el-table-column align="center" prop="releaseTime" label="发行时间" width="185">
      <template slot-scope="scope">
        <!-- 格式化日期 -->
        {{getFormat(scope.row.releaseTime)}}
      </template>
    </el-table-column>
    <el-table-column align="center" prop="createTime" label="创建时间" width="160">
      <template slot-scope="scope">
        <!-- 格式化日期 -->
        {{getFormat(scope.row.createTime)}}
      </template>
    </el-table-column>
    <el-table-column  align="center" label="操作">
      <template slot-scope="scope">
        <el-button icon="el-icon-video-play" type="primary" size="mini" @click="togglePlay(scope.row.songAddr)">试听</el-button>
<!--        <el-button icon="el-icon-search" type="primary" size="mini" @click="handleDetail(scope.row.id)">查看</el-button>-->
        <el-button icon="el-icon-edit-outline" type="success" size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button icon="el-icon-edit-outline" type="primary" size="mini" @click="handleSongList(scope.row.id)">分配歌单</el-button>
        <el-button icon="el-icon-set-up" type="info" size="mini" v-if="scope.row.status === 0" @click="handleRelease(scope.row.id, 1)">发布</el-button>
        <el-button icon="el-icon-set-up" type="info" size="mini" v-if="scope.row.status === 1" @click="handleRelease(scope.row.id, 0)">撤销发布</el-button>
        <el-button icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="query.current"
    :page-sizes="[10, 20, 50]"
    :page-size="query.size"
    layout="total, sizes, prev, pager, next, jumper"
    :total="query.total">
  </el-pagination>

  <!-- 查看详情弹窗 -->
  <detail :id="detail.id"  :visiable="detail.visiable" :remoteClose="remoteClose" />

  <!-- 添加弹窗 -->
  <add :visiable="add.visiable" :remoteClose="remoteClose" />

  <!-- 编辑弹窗 -->
  <edit :visiable="edit.visiable" :remoteClose="remoteClose" :id="edit.id"/>

  <!-- 分配歌单弹窗 -->
  <SongList :visiable="songList.visiable" :remoteClose="remoteClose" :id="songList.id"/>

  <!-- 上传excel的弹框 -->
  <el-dialog title="上传文件" :visible.sync="file.visiable" width="21%" :before-close="handleClose">
    <el-row>
      <el-upload ref="upload"
                 :show-file-list="true"
                 :auto-upload="false"
                 accept=".xls,.xlsx"
                 class="upload-demo"
                 drag
                 action=""
                 :http-request="uploadFile"
                 :before-upload="beforeUpload"
                 multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传.xls/.xlsx文件，且大小不超过1M</div>
      </el-upload>
    </el-row>
    <el-row class="upload_file_row">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="small" @click="submitUploadFile">上 传</el-button>
    </el-row>
  </el-dialog>
</div>
</template>

<script>
import {dateFormat} from '@/utils/date';
import musicApi from '@/api/music';
import Detail from "@/views/music/song/detail";
import {mapGetters} from "vuex";
import Add from './add';
import Edit from './edit';
import SongList from './songList';
export default {
  components:{
    Detail, Add, Edit, SongList
  },

  data() {
    return {
      batchDelFlag: true, // 批量删除标志
      multipleSelection: [],
      checkedSongIdsList: [], // 选中的歌曲ids
      list: [],   // 歌曲列表
      query: {
        songName: '',
        singerName: '',
        current: 1,   // 当前页码
        size: 10,     // 每页大小
        total: 0
      },  // 查询条件
      detail: {
        visiable: false,
        id: ''
      },
      add: {
        visiable: false
      },
      edit: {
        id: '',
        visiable: false
      },
      songList: {
        id: '',
        visiable: false
      },
      file: {
        visiable: false
      }
    }
  },

  computed:{
    ...mapGetters([
      'isPlay',
      'id',
      'url',
      'playButtonUrl',
      'picUrl',
      'title',
      'artist',
      'duration',
      'curTime',
      'listIndex',
      'listOfSongs',
      'autoNext',
    ])
  },

  created() {
    this.fetchData();
  },

  methods: {
    // 导入excel
    handleImport() {
      this.file.visiable = true;
    },

    // 播放音乐
    togglePlay(songAddr) {
      this.$store.commit('setIsPlay', !this.isPlay);
      this.$store.commit("setUrl", songAddr);
    },

    // 编辑
    handleEdit(id) {
      this.edit.id = id;
      this.edit.visiable = true;
    },

    // 分配歌单
    handleSongList(id) {
      this.songList.id = id;
      this.songList.visiable = true;
    },

    // 批量删除
    handleBatchDel() {
      this.$confirm('确认删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        musicApi.batchDel(this.checkedSongIdsList).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchData();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      // 文件类型
      const isType = file.type === 'application/vnd.ms-excel'
      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const fileType = isType || isTypeComputer
      if(!fileType) {
        this.$message.error('上传文件只能是xls/xlsx格式！')
      }

      // 文件大小限制为1M
      const fileLimit = file.size / 1024 / 1024 < 1;
      if(!fileLimit) {
        this.$message.error('上传文件大小不超过1M！');
      }
      return fileType && fileLimit
    },

    // 上传文件
    uploadFile(param) {
      const formData = new FormData() // FormData对象，添加参数只能通过append(\'key\', value)的形式添加
      formData.append('file', param.file) // 添加文件对象
      musicApi.batchSaveSong(formData).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '歌曲信息批量导入成功',
            type: 'success',
            duration: 1500
          });
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有操作权限，请联系管理员',
            duration: 1500
          });
        } else if (response.code === 15007) {
          this.$notify.error({
            title: '错误',
            message: '不能上传空文件',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        // 刷新列表
        this.fetchData();
        // 关闭上传文件的弹框
        this.handleClose();
      })
    },

    // 点击上传 手动上传到服务器 此时会触发组件的http-request
    submitUploadFile() {
      this.$refs.upload.submit()
    },

    // 选择
    handleSelectionChange(val) {
      this.checkedSongIdsList = [];
      this.multipleSelection = val;
      this.multipleSelection.forEach(item => {
        this.checkedSongIdsList.push(item.id);
      })
      this.batchDelFlag = this.checkedSongIdsList.length <= 0;
    },

    // 发布或者撤销发布
    handleRelease(id, status) {
      const form = {id, status};
      musicApi.updateRelease(form).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 1500
          });
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有操作权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        // 刷新列表
        this.fetchData();
      })
    },

    // 查询音乐列表
    fetchData() {
      musicApi.getAllMusic(this.query).then(response => {
        if (response.code === 200) {
          this.list = response.data.list;
          this.query.total = response.data.total;
        }
      })
    },

    // 查询歌曲详情
    handleDetail(id) {
      this.detail.id = id;
      this.detail.visiable = true;
    },

    // 打开添加弹框
    handleAdd() {
      this.add.visiable = true;
    },

    // 删除歌曲信息
    handleDel(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        musicApi.deleteSongById(id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchData();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 条件查询
    queryData() {
      this.fetchData();
    },

    // 重置
    reload() {
      this.query.singerName = '';
      this.query.songName = '';
      this.query.total = '';
      this.fetchData();
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.size = val;
      this.fetchData();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.current = val;
      this.fetchData();
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // 关闭上传文件的弹框
    handleClose() {
      this.file.visiable = false;
    },

    // 关闭窗口
    remoteClose() {
      this.detail.id = '';
      this.detail.visiable = false;
      this.add.visiable = false;
      this.edit.id = '';
      this.edit.visiable = false;
      this.songList.visiable = false;
      this.songList.id = '';
      this.fetchData();
    },
  },
}
</script>

<style scoped>
.handle_box {
  margin-bottom: 10px;
}

.upload_file_row {
  margin-top: 6px;
  margin-left: 230px;
}
</style>
